package top.so.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.so.dao.DraftsDao;
import top.so.dto.DraftsDTO;
import top.so.entity.Drafts;
import top.so.service.DraftsService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class DraftsServiceImpl implements DraftsService {
    @Autowired
    private DraftsDao draftsDao;

    public Boolean insertDrafts(DraftsDTO draftsDTO) {
        UUID uuid = UUID.randomUUID();
        draftsDTO.setDraftsID(String.valueOf(uuid).replaceAll("-",""));
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        draftsDTO.setGenTime(formatter.format(date));
        return draftsDao.insertDrafts(DTOToPOJO(draftsDTO));
    }


    public Boolean deleteDrafts(DraftsDTO draftsDTO) {
        return draftsDao.deleteDrafts(DTOToPOJO(draftsDTO));
    }

    public List<DraftsDTO> selectWithPage(DraftsDTO draftsDTO,int pageNum) {

        List<DraftsDTO> draftsDTOList = POJOToDTO(draftsDao.selectWithPage(DTOToPOJO(draftsDTO),pageNum));

        return draftsDTOList;
    }

    private Drafts DTOToPOJO(DraftsDTO draftsDTO) {
        Drafts drafts = new Drafts();
        if(draftsDTO!=null){
            drafts.setDraftsID(draftsDTO.getDraftsID());
            drafts.setDraftsName(draftsDTO.getDraftsName());
            drafts.setDraftsContent(draftsDTO.getDraftsContent());
            drafts.setUserID(draftsDTO.getUserID());
            drafts.setGenTime(draftsDTO.getGenTime());
        }
        return drafts;
    }
    private List<DraftsDTO> POJOToDTO(List<Drafts> draftsList) {
        List<DraftsDTO> draftsDTOList = new ArrayList<DraftsDTO>();
        DraftsDTO temp;
        for(Drafts drafts:draftsList){
            temp = new DraftsDTO();
            temp.setDraftsID(drafts.getDraftsID());
            temp.setDraftsName(drafts.getDraftsName());
            temp.setDraftsContent(drafts.getDraftsContent());
            temp.setUserID(drafts.getUserID());
            temp.setGenTime(drafts.getGenTime());
            draftsDTOList.add(temp);
        }
        return draftsDTOList;
    }
}
